開運算與閉運算:
1.1 用途:藉由圖像灰階、二值化與開閉運算,獲得遮罩(Mask),可應用在以下領域。
1.2 開運算
1.3 閉運算
1.4 程式碼
import cv2
import numpy as np
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './cookie.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (250, 250))
show_img('origin', image)
# 二值化
ret, mask1 = cv2.threshold(image, 160, 255, cv2.THRESH_BINARY)
show_img('mask_origin', mask1)
# 二值化+開運算
kernel=np.ones((5, 5), np.uint8)
ret, mask2 = cv2.threshold(image, 160, 255, cv2.THRESH_BINARY)
mask2 = cv2.morphologyEx(mask2, cv2.MORPH_OPEN, kernel, iterations=1)
show_img('OPEN', mask2)
# 二值化+閉運算
kernel=np.ones((5, 5),np.uint8)
ret, mask3 = cv2.threshold(image, 160, 255, cv2.THRESH_BINARY)
mask3 = cv2.morphologyEx(mask3, cv2.MORPH_CLOSE, kernel, iterations=1)
show_img('CLOSE', mask3)
1.5 執行結果
常用濾波器
2.1 Gaussian Filtering(線性濾波器)
import cv2
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './peach.jpg'
image = cv2.imread(image_path)
image = cv2.resize(image, (350, 350))
show_img('origin', image)
gaussian = cv2.GaussianBlur(image, (13, 13), 0)
show_img('GaussianBlur', gaussian)
2.2 Median Filtering(非線性濾波器)
import cv2
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './peach.jpg'
image = cv2.imread(image_path)
image = cv2.resize(image, (350, 350))
show_img('origin', image)
median = cv2.medianBlur(image, 13)
show_img('Median', median)
2.4 執行結果
讓我們繼續看下去...